package com.mzj.saas.mservice.smartlock.service.ruanku;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.Constant;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.enums.LockCallBackTypeEnum;
import com.mzj.saas.commons.enums.LockEventTypeEnum;
import com.mzj.saas.commons.enums.XzLockOperatorTypeEnum;
import com.mzj.saas.mservice.bill.entity.RentBill;
import com.mzj.saas.mservice.bill.repository.RentBillRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.repository.LockFrozenRepository;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.smartlock.service.SmartLockBrandService;
import com.mzj.saas.mservice.smartlock.sgin.RSAUtils;
import com.mzj.saas.mservice.smartlock.vo.LockCallBackVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 软库-回调
 *
 * @author shun
 * @createDate: 2021年6月25日 下午4:46:43
 * @version: 1.0
 */
@Service
public class SmartLockCallBackService {

    private static final Logger log = LoggerFactory.getLogger(SmartLockCallBackService.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private LockEventHandleService lockEventHandleService;
    @Autowired
    private LockCallBackHandleService lockCallBackHandleService;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private RentBillRepository rentBillRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private SmartLockBrandService smartLockBrandService;
    @Autowired
    private LockFrozenRepository lockFrozenRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SmartLockFingerprintRepository smartLockFingerprintRepository;

    /**
     * 智能锁回调url
     *
     * @param vo
     * @return
     */
    public Map<String, Object> lockCallback(LockCallBackVO vo) {

        log.info("软库, 智能锁回调/事件url------vo={}", vo.toString());

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("desc", "成功");
        result.put("code", 0);
        try {

            if (StringUtils.isBlank(vo.getPartnerKey()) || StringUtils.isBlank(vo.getSign()) || vo.getResult() == null
                    || StringUtils.isBlank(vo.getResult().toString())) {
                log.warn("参数错误");
                return result;
            }

            String accessKey = redisService.getValue(Constant.SSAS_ACCESS_KEY);
            if (!accessKey.equals(vo.getPartnerKey())) {
                log.warn("访问令牌错误 parntKey={}", vo.getPartnerKey());
                return result;
            }
            String securityKey = redisService.getValue(Constant.SSAS_SECURITY_KEY);
            String sign = RSAUtils.sign(vo.getTimestamp(), accessKey, vo.getRandomStr(), securityKey);

            if (!vo.getSign().equals(sign)) {
                log.warn("验签错误 callbackId={} ", vo.getCallBackId());
                return result;
            }

            if (StringUtils.isNotBlank(vo.getCallBackType())) {
                // 回调事件
                callBackType(vo);
            } else if (StringUtils.isNotBlank(vo.getEventType())) {
                // 事件推送
                eventType(vo);
            }
            return result;
        } catch (Exception e) {
            log.error("智能锁回调事件异常" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 回调事件处理
     *
     * @param vo
     */
    public void callBackType(LockCallBackVO vo) {
        try {
            log.info("智能锁回调事件处理  callbackType={}", vo.getCallBackType());

            LockCallBackTypeEnum typeEnum = LockCallBackTypeEnum.getLockType(vo.getCallBackType());

            switch (typeEnum) {
                case ADD_PWD:
                    lockCallBackHandleService.addPwdCallBack(vo);
                    break;
                case FREEZE_QR_UNFREEZE:
                    lockCallBackHandleService.freezeOrUnfreezeCallBack(vo);
                    break;
                case CLEAR_PWD:
                    lockCallBackHandleService.clearPwdCallBack(vo);
                    break;
                case CLEAR_ALL_PWD:
                    lockCallBackHandleService.clearAllCardCallBack(vo);
                    break;
                case ADD_CARD:
                    lockCallBackHandleService.addCardCallBack(vo);
                    break;
                case FREEZE_QR_UNFREEZE_CARD:
                    lockCallBackHandleService.freezeOrUnfreezeCardCallBack(vo);
                    break;
                case CLEAR_CARD:
                    lockCallBackHandleService.clearCardCallBack(vo);
                    break;
                case CLEAR_ALL_CARD:
                    lockCallBackHandleService.clearAllCardCallBack(vo);
                    break;
                default:
                    log.warn("智能锁回调事件处理 = {}", typeEnum.getCallBackType());
                    break;
            }

            // 更新智能锁授权人数
            updateOauthNumber(vo);

        } catch (Exception e) {
            log.error("智能锁回调处理异常" + e.getMessage(), e);
        }
    }

    /**
     * 事件推送
     *
     * @param vo
     */
    public void eventType(LockCallBackVO vo) {
        try {
            log.info("智能锁事件推送处理  eventType={}", vo.getEventType());
            LockEventTypeEnum typeEnum = LockEventTypeEnum.getLockType(vo.getEventType());
            switch (typeEnum) {
                case OFFLINE:
                    lockEventHandleService.lockOfflineCallBack(vo);
                    break;
                case OPEN_RECORD:
                    lockEventHandleService.openRecordCallBack(vo);
                    break;
                case LOW_BATTER:
                    lockEventHandleService.lowBatteryCallBack(vo);
                    break;
                default:
                    log.warn("智能锁事件推送处理  eventType={}", typeEnum.getEventType());
                    break;
            }
        } catch (Exception e) {
            log.error("智能锁事件推送异常" + e.getMessage(), e);
        }
    }

    /**
     * 账单过期冻结智能锁
     *
     * @param lockIds
     * @param type
     */
    public void backlogItemLock_bak(List<Long> lockIds, String type) {
        try {
            log.info("智能锁JOB冻结操作  size={}, type={}, lockIds={}", lockIds.size(), type, JSON.toJSONString(lockIds));

            if (CollectionUtils.isEmpty(lockIds)) {
                log.info("智能锁JOB冻结操作, lockIds is empty");
                return;
            }

            if (!"job-executor-frozen".equals(type) && !"job-executor-thaw".equals(type)) {
                log.info("智能锁JOB冻结操作, 不是JOB请求, 不处理");
                return;
            }

            log.info("账单过期{}智能锁  size={},type={}", "job-executor-frozen".equals(type) ? "冻结" : "解冻", lockIds.size(),
                    type);

            List<SmartLock> lockList = (List<SmartLock>) smartLockRepository.findAllById(lockIds);
            if (CollectionUtils.isEmpty(lockList)) {
                return;
            }

            // 冻结（1）或者解冻（0)
            Integer suspend = "job-executor-frozen".equals(type) ? 1 : 0;
            Date date = new Date();
            lockList.forEach(smartLock -> {
                Long lockId = smartLock.getId();
                List<SmartLockPwd> smartLockPwds = smartLockPwdRepository.findByLockId(lockId);
                List<Long> lockAuthIds = smartLockPwds.stream().map(SmartLockPwd::getLockAuthId)
                        .collect(Collectors.toList());

                List<SmartLockCard> smartLockCards = smartLockCardRepository.findByLockId(lockId);
                List<Long> cardAuthIds = smartLockCards.stream().map(SmartLockCard::getLockAuthId)
                        .collect(Collectors.toList());

                List<SmartLockFingerprint> fingerprints = smartLockFingerprintRepository.findByLockId(lockId);
                List<Long> fingerprintAuthIds = fingerprints.stream().map(SmartLockFingerprint::getLockAuthId)
                        .collect(Collectors.toList());

                lockAuthIds.addAll(cardAuthIds);
                lockAuthIds.addAll(fingerprintAuthIds);
                lockAuthIds = lockAuthIds.stream().distinct().collect(Collectors.toList());

                // 新增冻结/解冻记录
                String houseId = smartLock.getHouseId();
                String matchUserName = smartLock.getMatchUserName();
                String communityName = smartLock.getCommunityName();
                String buildName = smartLock.getBuildName();
                String unitName = smartLock.getUnitName();
                String roomNumber = smartLock.getRoomNumber();

                for (Long lockAuthId : lockAuthIds) {
                    LockFrozen lockFrozen = new LockFrozen();
                    lockFrozen.setType(suspend);
                    lockFrozen.setLockId(lockId);
                    lockFrozen.setLockAuditId(lockAuthId);
                    lockFrozen.setHouseId(houseId);
                    lockFrozen.setMatchUserName(matchUserName);
                    lockFrozen.setCommunityName(communityName);
                    lockFrozen.setBuildName(buildName);
                    lockFrozen.setUnitName(unitName);
                    lockFrozen.setRoomNumber(roomNumber);
                    lockFrozen.setOperationId(null);
                    lockFrozen.setOperationTime(date);
                    if (suspend == 1) {
                        lockFrozen.setReason("账单过期,系统冻结");
                    }
                    lockFrozenRepository.save(lockFrozen);
                }

                // 智能锁冻结原因
                if (suspend == 1) {
                    smartLock.setReason("账单过期,系统冻结");
                    smartLockRepository.save(smartLock);
                } else if (suspend == 0) {
                    smartLock.setReason(null);
                    smartLockRepository.save(smartLock);
                }

                // 密码授权明细
                for (SmartLockPwd pwd : smartLockPwds) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(pwd.getPwdIndex());
                    smartLockVO.setAuthInfoId(pwd.getLockAuthId());
                    Integer authType = pwd.getAuthType();
                    if (authType == 1 || authType == 2) {
                        smartLockVO.setAuthType("2");
                    } else if (authType == 3) {
                        smartLockVO.setAuthType("5");
                        smartLockVO.setTimes(pwd.getTimes());
                    }
                    smartLockVO.setSuspend(suspend);// 0:解冻 1:冻结
                    smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                    smartLockVO.setIdentification(pwd.getIdentification());
                    if (suspend == 1) {
                        String convert = DateUtils.format(date, DateUtils.FORMAT_DATETIME_14);
                        LockFrozen lockFrozen = lockFrozenRepository
                                .findByLockAuditIdAndOperationTime(pwd.getLockAuthId(), convert);
                        if (lockFrozen == null) {
                            lockFrozen = new LockFrozen();
                            lockFrozen.setType(suspend);
                            lockFrozen.setLockId(lockId);
                            lockFrozen.setLockAuditId(pwd.getLockAuthId());
                            lockFrozen.setHouseId(houseId);
                            lockFrozen.setMatchUserName(matchUserName);
                            lockFrozen.setCommunityName(communityName);
                            lockFrozen.setBuildName(buildName);
                            lockFrozen.setUnitName(unitName);
                            lockFrozen.setRoomNumber(roomNumber);
                            lockFrozen.setOperationId(null);
                            lockFrozen.setOperationTime(date);
                            if (suspend == 1) {
                                lockFrozen.setReason("账单过期,系统冻结");
                            }
                            lockFrozenRepository.save(lockFrozen);
                        }
                        smartLockVO.setLockFrozenId(lockFrozen.getId());
                    }
                    // 冻结密码硬件接口
                    smartLockBrandService.freezeOrUnfreeze(smartLockVO, smartLock.getBrandId(),
                            XzLockOperatorTypeEnum.PWD.getValue());
                }

                // 卡授权明细
                for (SmartLockCard card : smartLockCards) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(card.getCardIndex());
                    smartLockVO.setAuthInfoId(card.getLockAuthId());
                    smartLockVO.setSuspend(suspend);// 0:解冻 1:冻结
                    smartLockVO.setCardType(card.getType());
                    smartLockVO.setIndexNum(card.getCardIndexNum());
                    smartLockVO.setIdentification(card.getIdentification());
                    // 冻结卡硬件接口
                    smartLockBrandService.freezeOrUnfreezeCard(smartLockVO, smartLock.getBrandId(),
                            XzLockOperatorTypeEnum.CARD.getValue());
                }

                // 指纹锁
                for (SmartLockFingerprint fingerprint : fingerprints) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(fingerprint.getFingerprintIndex());
                    smartLockVO.setAuthInfoId(fingerprint.getLockAuthId());
                    smartLockVO.setSuspend(suspend);// 0:解冻 1:冻结
                    // smartLockVO.setCardType(fingerprint.getType());
                    smartLockVO.setIndexNum(fingerprint.getFingerprintIndexNum());
                    // 指纹硬件接口 1密码 2卡 3指纹
                    smartLockBrandService.freezeOrUnfreezeFingerprint(smartLockVO, smartLock.getBrandId(),
                            XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                }
            });

        } catch (Exception e) {
            log.error("账单过期冻结智能锁异常" + e.getMessage(), e);
        }
    }

    /**
     * 账单过期冻结智能锁
     * 支持按锁或者按承租人冻结/解冻
     *
     * @param map
     * @param type
     * @author shun
     * @date 2021年7月13日
     */
    public void backlogItemLock(Map<String, List<Long>> map, String type) {
        try {
            List<Long> lockIds = map.get("lockIds");
            List<Long> billIds = map.get("billIds");

            log.info("智能锁JOB冻结/解冻操作  size={}, type={}, lockIds={}, billIds={}", lockIds.size(), type, JSON.toJSONString(lockIds), JSON.toJSONString(billIds));
            if (CollectionUtils.isEmpty(lockIds) || CollectionUtils.isEmpty(billIds)) {
                log.info("智能锁JOB冻结/解冻操作, lockIds/billIds is empty");
                return;
            }

            if (!"job-executor-frozen".equals(type) && !"job-executor-thaw".equals(type)) {
                log.info("智能锁JOB冻结/解冻操作, 不是JOB请求, 不处理");
                return;
            }

            log.info("账单过期{}智能锁  size={}, type={}", "job-executor-frozen".equals(type) ? "冻结" : "解冻", lockIds.size(),
                    type);


            List<SmartLock> lockList = (List<SmartLock>) smartLockRepository.findAllById(lockIds);
            if (CollectionUtils.isEmpty(lockList)) {
                return;
            }

            List<String> houseIds = lockList.stream().map(SmartLock::getHouseId).collect(Collectors.toList());
            List<House> houses = houseRepository.findByIdIn(houseIds);
            // 账单列表
            List<RentBill> rentBillList = rentBillRepository.findByIdIn(billIds);

            // 冻结（1）或者解冻（0)
            Integer suspend = "job-executor-frozen".equals(type) ? 1 : 0;
            Date date = new Date();

            // 按账单冻结
            for (RentBill r : rentBillList) {
                Boolean flag = false;
                // 验证当前订单是否为多承租人订单
                for (House h : houses) {
                    if (r.getHouseId().equals(h.getId()) && h.getMatchType() != null && h.getMatchType() == 2) {
                        flag = true;
                        break;
                    }
                }

                for (SmartLock smartLock : lockList) {
                    if (smartLock.getHouseId().equals(r.getHouseId())) {
                        List<Long> lockAuthIds = new ArrayList<>();
                        List<SmartLockPwd> smartLockPwds = new ArrayList<>();
                        List<SmartLockFingerprint> fingerprints = new ArrayList<>();
                        List<SmartLockCard> smartLockCards = new ArrayList<>();
                        if (flag) {
                            // 多承租人模式，按承租人冻结/解冻
                            List<SmartLockAuth> authList = smartLockAuthRepository.finHouseIdAndMatchUserId(r.getHouseId(), r.getMatchUserId());
                            for (SmartLockAuth auth : authList) {

                                if (auth.getPwdStatus() != null && auth.getPwdStatus() == 1) {
                                    SmartLockPwd smartLockPwd = smartLockPwdRepository.findByLockAuthId(auth.getId());
                                    if (smartLockPwd != null) {
                                        smartLockPwds.add(smartLockPwd);
                                    }
                                }

                                if (auth.getCardStatus() != null && auth.getCardStatus() == 1) {
                                    SmartLockCard card = smartLockCardRepository.findByLockAuthIdAndType(auth.getId(), 1);
                                    if (card != null) {
                                        smartLockCards.add(card);
                                    }
                                }

                                if (auth.getCardStatus() != null && auth.getCpuStatus() == 1) {
                                    SmartLockCard cpu = smartLockCardRepository.findByLockAuthIdAndType(auth.getId(), 2);
                                    if (cpu != null) {
                                        smartLockCards.add(cpu);
                                    }
                                }

                                if (auth.getFingerprintStatus() != null && auth.getFingerprintStatus() == 1) {
                                    fingerprints = smartLockFingerprintRepository.findByLockAuthId(auth.getId());
                                }
                            }

                            lockAuthIds = authList.stream().map(SmartLockAuth::getId).collect(Collectors.toList());

                        } else {
                            // 单承租人, 按锁冻结
                            smartLockPwds = smartLockPwdRepository.findByLockId(smartLock.getId());
                            lockAuthIds = smartLockPwds.stream().map(SmartLockPwd::getLockAuthId)
                                    .collect(Collectors.toList());

                            smartLockCards = smartLockCardRepository.findByLockId(smartLock.getId());
                            List<Long> cardAuthIds = smartLockCards.stream().map(SmartLockCard::getLockAuthId)
                                    .collect(Collectors.toList());

                            fingerprints = smartLockFingerprintRepository.findByLockId(smartLock.getId());
                            List<Long> fingerprintAuthIds = fingerprints.stream().map(SmartLockFingerprint::getLockAuthId)
                                    .collect(Collectors.toList());

                            lockAuthIds.addAll(cardAuthIds);
                            lockAuthIds.addAll(fingerprintAuthIds);
                            lockAuthIds = lockAuthIds.stream().distinct().collect(Collectors.toList());
                        }
                        if (CollectionUtils.isEmpty(lockAuthIds)) {
                            log.info("无智能锁授权信息");
                            break;
                        }

                        // 新增冻结/解冻记录
                        String houseId = smartLock.getHouseId();
                        String matchUserName = smartLock.getMatchUserName();
                        String communityName = smartLock.getCommunityName();
                        String buildName = smartLock.getBuildName();
                        String unitName = smartLock.getUnitName();
                        String roomNumber = smartLock.getRoomNumber();

                        List<LockFrozen> LockFrozenList = new ArrayList<>();
                        for (Long authId : lockAuthIds) {
                            LockFrozen lockFrozen = new LockFrozen();
                            lockFrozen.setType(suspend);
                            lockFrozen.setLockId(smartLock.getId());
                            lockFrozen.setLockAuditId(authId);
                            lockFrozen.setHouseId(houseId);
                            lockFrozen.setMatchUserName(matchUserName);
                            lockFrozen.setCommunityName(communityName);
                            lockFrozen.setBuildName(buildName);
                            lockFrozen.setUnitName(unitName);
                            lockFrozen.setRoomNumber(roomNumber);
                            lockFrozen.setOperationId(null);
                            lockFrozen.setOperationTime(date);
                            if (suspend == 1) {
                                lockFrozen.setReason("账单过期,系统冻结");
                            }

                            LockFrozenList.add(lockFrozen);
                        }
                        lockFrozenRepository.saveAll(LockFrozenList);

                        // 智能锁冻结原因
                        if (suspend == 1) {
                            smartLock.setReason("账单过期,系统冻结");
                            smartLockRepository.save(smartLock);
                        } else if (suspend == 0) {
                            smartLock.setReason(null);
                            smartLockRepository.save(smartLock);
                        }

                        // 密码授权明细
                        for (SmartLockPwd pwd : smartLockPwds) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(pwd.getPwdIndex());
                            smartLockVO.setAuthInfoId(pwd.getLockAuthId());
                            smartLockVO.setIdentification(pwd.getIdentification());
                            Integer authType = pwd.getAuthType();
                            if (authType == 1 || authType == 2) {
                                smartLockVO.setAuthType("2");
                            } else if (authType == 3) {
                                smartLockVO.setAuthType("5");
                                smartLockVO.setTimes(pwd.getTimes());
                            }
                            smartLockVO.setSuspend(suspend);// 0:解冻 1:冻结
                            smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                            if (suspend == 1) {
                                String convert = DateUtils.format(date, DateUtils.FORMAT_DATETIME_14);
                                LockFrozen lockFrozen = lockFrozenRepository
                                        .findByLockAuditIdAndOperationTime(pwd.getLockAuthId(), convert);
                                if (lockFrozen == null) {
                                    lockFrozen = new LockFrozen();
                                    lockFrozen.setType(suspend);
                                    lockFrozen.setLockId(smartLock.getId());
                                    lockFrozen.setLockAuditId(pwd.getLockAuthId());
                                    lockFrozen.setHouseId(houseId);
                                    lockFrozen.setMatchUserName(matchUserName);
                                    lockFrozen.setCommunityName(communityName);
                                    lockFrozen.setBuildName(buildName);
                                    lockFrozen.setUnitName(unitName);
                                    lockFrozen.setRoomNumber(roomNumber);
                                    lockFrozen.setOperationId(null);
                                    lockFrozen.setOperationTime(date);
                                    if (suspend == 1) {
                                        lockFrozen.setReason("账单过期,系统冻结");
                                    }
                                    lockFrozenRepository.save(lockFrozen);
                                }
                                smartLockVO.setLockFrozenId(lockFrozen.getId());
                            }
                            // 冻结密码硬件接口
                            smartLockBrandService.freezeOrUnfreeze(smartLockVO, smartLock.getBrandId(),
                                    XzLockOperatorTypeEnum.PWD.getValue());

                        }

                        // 卡授权明细
                        for (SmartLockCard card : smartLockCards) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(card.getCardIndex());
                            smartLockVO.setAuthInfoId(card.getLockAuthId());
                            smartLockVO.setSuspend(suspend);// 0:解冻 1:冻结
                            smartLockVO.setCardType(card.getType());
                            smartLockVO.setIndexNum(card.getCardIndexNum());
                            smartLockVO.setIdentification(card.getIdentification());
                            // 冻结卡硬件接口
                            smartLockBrandService.freezeOrUnfreezeCard(smartLockVO, smartLock.getBrandId(),
                                    XzLockOperatorTypeEnum.CARD.getValue());
                        }

                        // 指纹锁
                        for (SmartLockFingerprint fingerprint : fingerprints) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(fingerprint.getFingerprintIndex());
                            smartLockVO.setAuthInfoId(fingerprint.getLockAuthId());
                            smartLockVO.setSuspend(suspend);// 0:解冻 1:冻结
                            // smartLockVO.setCardType(fingerprint.getType());
                            smartLockVO.setIndexNum(fingerprint.getFingerprintIndexNum());
                            // 指纹硬件接口 1密码 2卡 3指纹
                            smartLockBrandService.freezeOrUnfreezeFingerprint(smartLockVO, smartLock.getBrandId(),
                                    XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                        }

                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("账单过期冻结智能锁异常" + e.getMessage(), e);
        }
    }

    /**
     * 更新智能锁授权人数
     *
     * @param vo
     */
    public void updateOauthNumber(LockCallBackVO vo) {
        try {
            String sn = vo.getSn();
            log.warn("更新智能锁授权人数 sn={}", sn);
            SmartLock smartLock = smartLockRepository.findBySn(sn);

            if (smartLock == null) {
                log.warn("更新智能锁授权人数 sn值未找到锁 sn={}", sn);
                return;
            }
            Long lockId = smartLock.getId();
            Integer bindType = smartLock.getBindType();
            Integer bindStatus = smartLock.getBindStatus();

            int oauthNumber = 0;
            if (bindType == 1 && bindStatus == 1) {// 单位锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 0);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }

            } else if (bindType == 2 && bindStatus == 2) {// 个人锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 1);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }
            }

            smartLock.setOauthNumber(oauthNumber);
            smartLockRepository.save(smartLock);
        } catch (Exception e) {
            log.error("更新智能锁授权人数异常" + e.getMessage(), e);
        }
    }

}
